﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace USERS.CYT369.COM.Models.Ticket
{
    public class UserTicket
    {
        public UserTicket(string ticket, string appId, USERS.CYT369.COM.MODELS.SysUser user, DateTime expiredTime)
        {
            this.Ticket = ticket;
            this.SysUser = user;
            this.AppID = appId;
            this.ExpiredTime = expiredTime;
        }

        /// <summary>
        /// 登录账户ticket
        /// </summary>
        public string Ticket { get; set; }

        /// <summary>
        /// 登录账户
        /// </summary>
        public USERS.CYT369.COM.MODELS.SysUser SysUser { get; set; }

        /// <summary>
        /// 登录过期时间
        /// </summary>
        public DateTime ExpiredTime { get; set; }

        /// <summary>
        ///  首登录APP
        /// </summary>
        public string AppID { get; set; }
    }

    public class TicketService
    {
        private static readonly TicketService m_Instane = new TicketService();
        private Dictionary<string, UserTicket> m_TicketCache = new Dictionary<string, UserTicket>();

        private TicketService() { }

        public static TicketService Instane
        {
            get
            {
                return m_Instane;
            }
        }

        public UserTicket GetTicket(string ticket)
        {
            if (m_TicketCache.ContainsKey(ticket))
            {
                return m_TicketCache[ticket];
            }

            return null;
        }

        public void AddTicket(string ticket, string appId, USERS.CYT369.COM.MODELS.SysUser user, DateTime expiredTime)
        {
            if (m_TicketCache.ContainsKey(ticket))
            {
                var v = m_TicketCache[ticket];
                v.AppID = appId;
                v.SysUser = user;
                v.ExpiredTime = expiredTime;
            }
            else
            {
                m_TicketCache.Add(ticket, new UserTicket(ticket, appId, user, expiredTime));
            }
        }

        public void RemoveTicket(string ticket)
        {
            if (m_TicketCache.ContainsKey(ticket))
            {
                m_TicketCache.Remove(ticket);
            }
        }

        /// <summary>
        /// 自动清除过期信息
        /// </summary>
        public void AutoClearCache()
        {
            new System.Threading.Tasks.Task(delegate ()
            {
                var now = DateTime.Now;
                var expiredList = new List<string>();
                foreach (var k in m_TicketCache.Keys)
                {
                    var v = m_TicketCache[k];
                    if (now >= v.ExpiredTime)
                    {
                        expiredList.Add(k);
                    }
                }

                foreach (var k in expiredList)
                {
                    m_TicketCache.Remove(k);
                }
            }).Start();
        }

    }

}
